package com.mayuanfei.springboot15.config;

import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.config.GlobalSerializerConfig;
import com.hazelcast.config.SerializerConfig;
import com.hazelcast.core.HazelcastInstance;
import com.mayuanfei.springboot15.pojo.UserInfo2;
import com.mayuanfei.springboot15.serializer.GlobalStreamSerializer;
import com.mayuanfei.springboot15.serializer.UserInfo2Serializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * hazelcast配置类
 *
 * @author 老马
 * @date 2023-07-07 14:17
 */
@EnableCaching
@Configuration
public class HazelcastConfig {

    @Bean
    public ClientConfig config() {
        ClientConfig clientConfig = new ClientConfig();
        // 设置Hazelcast实例名称
        clientConfig.setInstanceName("hazelcast-client-instance");
        // 设置集群名称.这个参数很重要,一定要和搭建集群时名称一致.默认是dev
        clientConfig.setClusterName("lmcache");
        // 设置集群服务器的地址
        clientConfig.getNetworkConfig().addAddress("172.17.236.59");
        // 配置序列化器
        SerializerConfig sc = new SerializerConfig()
                .setImplementation(new UserInfo2Serializer())
                .setTypeClass(UserInfo2.class);
        clientConfig.getSerializationConfig().addSerializerConfig(sc);
        // 配置全局序列化器
        GlobalSerializerConfig gc = new GlobalSerializerConfig()
                .setImplementation(new GlobalStreamSerializer())
                .setOverrideJavaSerialization(true);
        clientConfig.getSerializationConfig().setGlobalSerializerConfig(gc);
        return clientConfig;
    }

    /**
     * 这里默认就会调用HazelcastClient.newHazelcastClient方法.
     * 为了便于理解,加入此方法.
     */
    @Bean
    public HazelcastInstance hazelcastInstance(ClientConfig config) {
        return HazelcastClient.newHazelcastClient(config);
    }

}